package com.client.controller;

import com.client.pojo.Entries;
import com.client.pojo.Users;
import com.client.service.EntriesService;
import com.client.service.UsersService;
import com.client.utils.JwtUtils;
import com.client.utils.ResponseMsg;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 词条表 前端控制器
 * </p>
 *
 * @author ckick
 * @since 2025-09-20 08:28:54
 */
@RestController
@RequestMapping("/entries")
public class EntriesController {

    @Autowired
    private EntriesService entriesService;

    @Autowired
    private UsersService usersService;

    @RequestMapping("addEntries")
    public ResponseMsg addEntries(@RequestBody Map<String, Object> formData) {
        System.out.println("增加词条" + formData);

        // 获取并验证用户ID（前端传递的是publishId）
        Integer publisherId = (Integer) formData.get("publishId");
        if (publisherId == null || publisherId <= 0) {
            System.out.println("用户未登录");
            return ResponseMsg.getInstance(-201, "用户未登录，请先登录");
        }

        // 验证用户是否存在
        Users currentUser = usersService.getById(publisherId);
        if (currentUser == null) {
            System.out.println("用户不存在");
            return ResponseMsg.getInstance(-202, "用户不存在");
        }

        // 验证标题是否为空
        String entryName = (String) formData.get("entryName");
        if (entryName == null || entryName.trim().isEmpty()) {
            System.out.println("标题不能为空");
            return ResponseMsg.getInstance(ResponseMsg.ERROR, "标题不能为空");
        }

        // 验证内容是否为空
        String description = (String) formData.get("description");
        if (description == null || description.trim().isEmpty()) {
            System.out.println("内容不能为空");
            return ResponseMsg.getInstance(ResponseMsg.ERROR, "内容不能为空");
        }

        // 验证分类是否为空
        Integer categoryId = (Integer) formData.get("categoryId");
        if (categoryId == null || categoryId <= 0) {
            System.out.println("分类不能为空");
            return ResponseMsg.getInstance(ResponseMsg.ERROR, "请选择分类");
        }

        // 构建Entries对象
        Entries entries = new Entries();
        entries.setEntryName(entryName);
        entries.setDescription(description);
        entries.setCategoryId(categoryId);
        entries.setPublisherId(publisherId);
        entries.setSource((String) formData.get("source"));
        entries.setEntriesPic((String) formData.get("entriesPic"));
        entries.setCreatedAt(new Date());

        String[] sensitiveWord ={"死","操你妈","逼","傻"};
        for (int i = 0; i < sensitiveWord.length; i++) {
            if (description.contains(sensitiveWord[i])){
                return ResponseMsg.getInstance(ResponseMsg.ERROR, "词条发布失败,包含敏感词");
            }
        }

        try {
            boolean saveResult = entriesService.save(entries);
            if (saveResult) {
                return ResponseMsg.getInstance(ResponseMsg.SUCCESS, "词条发布成功", entries);
            } else {
                return ResponseMsg.getInstance(ResponseMsg.ERROR, "词条发布失败");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseMsg.getInstance(ResponseMsg.ERROR, "系统错误，发布失败");
        }
    }
    /**
     * 分页查询词条列表（不包含用户头像信息）
     * @param param 分页参数
     * @return 分页结果JSON字符串
     */
    @PostMapping("getEntries")
    public String getEntries(@RequestBody Map<String, Object> param) {
        Integer page = (Integer) param.get("page");
        Integer limit = (Integer) param.get("limit");
        com.baomidou.mybatisplus.extension.plugins.pagination.Page<Entries> pageWrapper = new com.baomidou.mybatisplus.extension.plugins.pagination.Page<>(page, limit);
        com.baomidou.mybatisplus.core.conditions.query.QueryWrapper<Entries> queryWrapper = new com.baomidou.mybatisplus.core.conditions.query.QueryWrapper<>();
        queryWrapper.orderByDesc("entry_id");
        IPage<Entries> result = entriesService.page(pageWrapper, queryWrapper);
        return JSON.toJSONString(result);
    }

    /**
     * 根据ID查询词条详情及发布者信息（包含头像）
     * @param entryId 词条ID
     * @return 词条详情JSON字符串
     */
    @PostMapping("searchById")
    public String getEntryDetail(@RequestBody Map<String, Object> param) {
        Integer entryId = null;
        try {
            // 获取entryId参数并进行类型检查和转换
            Object idObj = param.get("entryId");
            if (idObj instanceof Integer) {
                entryId = (Integer) idObj;
            } else if (idObj instanceof String) {
                // 如果是String类型，尝试转换为Integer
                entryId = Integer.parseInt((String) idObj);
            } else {
                System.out.println("entryId类型错误: " + idObj);
                return "{\"error\":\"entryId参数类型错误\"}";
            }
            
            if (entryId == null || entryId <= 0) {
                System.out.println("entryId无效: " + entryId);
                return "{\"error\":\"无效的词条ID\"}";
            }
        } catch (NumberFormatException e) {
            System.out.println("entryId格式错误: " + e.getMessage());
            return "{\"error\":\"词条ID格式错误\"}";
        }
        
        Entries entry = entriesService.getEntryByIdWithUser(entryId);
        System.out.println("查询词条详情"+JSON.toJSONString(entry));
        return JSON.toJSONString(entry);
    }

    /**
     * 分页查询词条列表及发布者头像信息
     * @param param 包含分页参数和查询条件的Map
     * @return 分页结果JSON字符串
     */
    @PostMapping("/listWithUser")
    public String getEntriesListWithUser(@RequestBody Map<String, Object> param) {
        Integer page = (Integer) param.get("page");
        Integer limit = (Integer) param.get("limit");

        // 调用服务层方法获取包含用户头像的词条列表
        IPage<Entries> result = entriesService.getEntriesPageWithUserAvatar(page, limit);

        return JSON.toJSONString(result);
    }

    @PostMapping("hotList")
    public String getHotList(@RequestBody Map<String, Object> param) {
        Integer page = (Integer) param.get("page");
        Integer limit = (Integer) param.get("limit");

        // 调用服务层方法获取包含用户头像的词条列表
        IPage<Entries> result = entriesService.getHot(page, limit);
        return JSON.toJSONString(result);
    }


    @PostMapping("addViews")
    public String addViews(@RequestBody Map<String, Object> param) {
        //TODO: process POST request
        Integer entryId = (Integer) param.get("entryId");
        System.out.println("增加视图"+entryId);
        entriesService.addViews(entryId);
        return "success";
    }

    @PostMapping("addLikes")
    public String addLikes(@RequestBody Map<String, Object> param) {
        //TODO: process POST request
        Integer entryId = (Integer) param.get("entryId");
        System.out.println("增加点赞"+entryId);
        entriesService.addLikes(entryId);
        return "success";
    }
    
    @PostMapping("addCollects")
    public String addCollects(@RequestBody Map<String, Object> param) {
        //TODO: process POST request
        Integer entryId = (Integer) param.get("entryId");
        System.out.println("增加收藏"+entryId);
        entriesService.addCollects(entryId);
        return "success";
    }
    
    //取消点赞
    @PostMapping("cancelLikes")
    public String cancelLikes(@RequestBody Map<String, Object> param) {
        //TODO: process POST request
        Integer entryId = (Integer) param.get("entryId");
        System.out.println("取消点赞"+entryId);
        entriesService.cancelLikes(entryId);
        return "success";
    }
    //取消收藏
    @PostMapping("cancelCollects")
    public String cancelCollects(@RequestBody Map<String, Object> param) {
        //TODO: process POST request
        Integer entryId = (Integer) param.get("entryId");
        System.out.println("取消收藏"+entryId);
        entriesService.cancelCollects(entryId);
        return "success";
    }

    //根据关键词搜索词条
    @PostMapping("searchEntry")
    public String searchEntry(@RequestBody Map<String, Object> param) {
        //TODO: process POST request
        String word = (String) param.get("keyword");
        String keyword = "%"+word+"%";
        Integer page = (Integer) param.get("page");
        Integer limit = (Integer) param.get("limit");
        Integer offset =(page-1)*limit;

        List<Entries> list = entriesService.searchEntry(keyword, offset, limit);
        return JSON.toJSONString(list);
    }
    //搜索分类的词条（逻辑和listWithUser一样，只是Mapper加了一个条件）
    @PostMapping("searchFirstCategory")
    public String searchFirstCategory(@RequestBody Map<String, Object> param) {
        //把字符串转换为整数
        Integer categoryId = Integer.parseInt((String) param.get("categoryId"));
        Integer page = (Integer) param.get("page");
        Integer limit = (Integer) param.get("limit");
        Integer offset =(page-1)*limit;

        List<Entries> list = entriesService.searchFirstCategory(categoryId, offset, limit);
        System.out.println("搜索第一分类的词条"+JSON.toJSONString(list));
        return JSON.toJSONString(list);
    }
}
